<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Crypt;

class CheckToken
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        //用户不存在
        if(empty($request->token)) {
            return response()->json(['code' => 2, 'message' => '用户登陆失效，请重新登陆', 'data' => '']);
        }

        //查询用户token
        $user = DB::table('users')->where('remember_token', $request->token)->first();

        if(empty($user)) {
            return response()->json(['code' => 2, 'message' => '用户登陆失效，请重新登陆', 'data' => '']);
        }

        if(Crypt::decryptString($request->token) != $user->id) {
            return response()->json(['code' => 2, 'message' => '用户登陆失效，请重新登陆', 'data' => '']);
        }

        //将用户ID放入request参数域里
        $request->u_id = $user->id;

        return $next($request);
    }
}
